﻿﻿@model WebApp.Models.Customer
<!-- 弹出编辑窗体表单 -->
<div id="customerdetailwindow" class="easyui-window"
     title="明细数据"
     data-options="modal:true,
                    closed:true,
                    minimizable:false,
                    collapsible:false,
                    maximized:false,
                    iconCls:'icon-more',
                    footer:'#windowfooter',
                    closeDuration:200,
                    closeAnimation:'slide',
                    openDuration:300,
                    openAnimation:'slide',
                    onBeforeClose:function(){
                      var that = $(this);
                      if(customerhasmodified()){
                        $.messager.confirm('确认','你确定要放弃保存修改的记录?',function(r){
                        if (r){
                          var opts = that.panel('options');
                          var onBeforeClose = opts.onBeforeClose;
                          opts.onBeforeClose = function(){};
                          that.panel('close');
                          opts.onBeforeClose = onBeforeClose;
                          hook = false;
                        }
                        });
                        return false;
                      }
                    },
                    onOpen:function(){
                       $(this).window('vcenter');
                       $(this).window('hcenter');
                    },
                    onRestore:function(){
                      $customerwaterrecordsdg.datagrid('resize');
                      $customerwatermetersdg.datagrid('resize');
                      $customerwaterquotasdg.datagrid('resize');
                    },
                    onMaximize:function(){
                      $customerwaterrecorddg.datagrid('resize');
                      $customerwatermeterdg.datagrid('resize');
                      $customerwaterquotadg.datagrid('resize');
                    }
                    " style="width:800px;height:450px;display:none">
  <!-- toolbar -->
  <div class="panel-content py-2 rounded-bottom border-faded border-left-0 border-right-0  text-muted bg-subtlelight-fade sticky-top">
    <div class="row align-items-center m-0">
      <div class="col">
        <div class="btn-group btn-group-sm">
          <button name="saveitembutton" onclick="savecustomeritem()" class="btn btn-default">
            <i class="fal fa-save"></i> @Html.L("Save")
          </button>
        </div>
        <div class="btn-group btn-group-sm" id="deleteitem-btn-group">
          <button onclick="deletecustomeritem()" class="btn btn-danger">
            <i class="fal fa-times"></i> @Html.L("Delete")
          </button>
        </div>

      </div>
      <div class="col d-flex">

      </div>
    </div>
  </div>
  <!-- panel container form  -->
  <div class="panel-container show">
    <div class="panel-content">
      <form id="customer_form"
            class="easyui-form form-horizontal padding-10"
            method="post"
            data-options="novalidate:true,
                            onChange: function(target){
                              hook = true;
                              $('button[name*=\'saveitembutton\']').prop('disabled', false);
                             },
                             onLoadSuccess:function(data){
                               hook = false;
                               $('button[name*=\'saveitembutton\']').prop('disabled', true);
                             }">
        @Html.AntiForgeryToken()
        <!--Primary Key-->
        @Html.HiddenFor(model => model.Id)
        @Html.HiddenFor(model => model.Dept)
        @Html.HiddenFor(model => model.Threshold)
        <fieldset class="form-group">
          <div class="row m-1">

            <!--单位名称-->
            <label class="col-md-2 mb-1 form-label text-right text-danger">@Html.DisplayNameFor(model => model.Code)</label>
            <div class="col-md-4 mb-1">
              <input id="@Html.IdFor(model => model.Code)"
                     name="@Html.NameFor(model => model.Code)"
                     value="@Html.ValueFor(model => model.Code)"
                     tabindex="0" required
                     class="easyui-textbox"
                     style="width:100%"
                     type="text"
                     data-options="prompt:'@Html.DisplayNameFor(model => model.Code)',
								 required:true, validType: 'length[0,50]'
                                 " />
            </div>

            <!--单位名称-->
            <label class="col-md-2 mb-1 form-label text-right text-danger">@Html.DisplayNameFor(model => model.Name)</label>
            <div class="col-md-4 mb-1">
              <input id="@Html.IdFor(model => model.Name)"
                     name="@Html.NameFor(model => model.Name)"
                     value="@Html.ValueFor(model => model.Name)"
                     tabindex="0" required
                     class="easyui-textbox"
                     style="width:100%"
                     type="text"
                     data-options="prompt:'@Html.DisplayNameFor(model => model.Name)',
								 required:true,
                                 validType: 'length[0,50]'
                                 " />
            </div>
            <!--单位业态-->
            <label class="col-md-2 mb-1 form-label text-right text-danger">@Html.DisplayNameFor(model => model.Category)</label>
            <div class="col-md-4 mb-1">
              <input id="@Html.IdFor(model => model.Category)"
                     name="@Html.NameFor(model => model.Category)"
                     value="@Html.ValueFor(model => model.Category)"
                     tabindex="1"
                     class="easyui-combobox"
                     style="width:100%"
                     type="text"
                     data-options="prompt:'@Html.DisplayNameFor(model => model.Category)',
								 required:true,data:categorydatasource,editable:false,panelHeight:'auto'
                                 " />
            </div>
            <!--状态-->
            <label class="col-md-2 mb-1 form-label text-right ">@Html.DisplayNameFor(model => model.Status)</label>
            <div class="col-md-4 mb-1">
              <input id="@Html.IdFor(model => model.Status)"
                     name="@Html.NameFor(model => model.Status)"
                     value="@Html.ValueFor(model => model.Status)"
                     tabindex="11"
                     class="easyui-textbox"
                     style="width:100%"
                     type="text"
                     data-options="prompt:'@Html.DisplayNameFor(model => model.Status)',
								 required:false,readonly:true,
                                 " />
            </div>
            <!--主要联系人-->
            <label class="col-md-2 mb-1 form-label text-right ">@Html.DisplayNameFor(model => model.Contact)</label>
            <div class="col-md-4 mb-1">
              <input id="@Html.IdFor(model => model.Contact)"
                     name="@Html.NameFor(model => model.Contact)"
                     value="@Html.ValueFor(model => model.Contact)"
                     tabindex="3"
                     class="easyui-textbox"
                     style="width:100%"
                     type="text"
                     data-options="prompt:'@Html.DisplayNameFor(model => model.Contact)',
								 required:false,
                                 validType: 'length[0,50]'
                                 " />
            </div>


            <!--联系方式-->
            <label class="col-md-2 mb-1 form-label text-right ">@Html.DisplayNameFor(model => model.ContactInfo)</label>
            <div class="col-md-4 mb-1">
              <input id="@Html.IdFor(model => model.ContactInfo)"
                     name="@Html.NameFor(model => model.ContactInfo)"
                     value="@Html.ValueFor(model => model.ContactInfo)"
                     tabindex="4"
                     class="easyui-textbox"
                     style="width:100%"
                     type="text"
                     data-options="prompt:'@Html.DisplayNameFor(model => model.ContactInfo)',
								 required:false,     validType: 'email'
                                 " />
            </div>

            <!--短信通知手机号-->
            <label class="col-md-2 mb-1 form-label text-right ">@Html.DisplayNameFor(model => model.MobilePhone)</label>
            <div class="col-md-4 mb-1">
              <input id="@Html.IdFor(model => model.MobilePhone)"
                     name="@Html.NameFor(model => model.MobilePhone)"
                     value="@Html.ValueFor(model => model.MobilePhone)"
                     tabindex="5"
                     class="easyui-textbox"
                     style="width:100%"
                     type="text"
                     data-options="prompt:'@Html.DisplayNameFor(model => model.MobilePhone)',
								 required:false,
                                 validType: 'length[0,50]'
                                 " />
            </div>
            <!--单价-->
            <label class="col-md-2 mb-1 form-label text-right text-danger">@Html.DisplayNameFor(model => model.WaterPrice)</label>
            <div class="col-md-4 mb-1">
              <input id="@Html.IdFor(model => model.WaterPrice)"
                     name="@Html.NameFor(model => model.WaterPrice)"
                     value="@Html.ValueFor(model => model.WaterPrice)"
                     tabindex="9"
                     class="easyui-numberspinner"
                     style="width:100%"
                     type="text"
                     data-options="prompt:'@Html.DisplayNameFor(model => model.WaterPrice)',
								 required:true,  precision:3,

                                 " />

            </div>

            <!--单位业态-->
            <label class="col-md-2 mb-1 form-label text-right text-danger">@Html.DisplayNameFor(model => model.Type)</label>
            <div class="col-md-4 mb-1">
              <input id="@Html.IdFor(model => model.Type)"
                     name="@Html.NameFor(model => model.Type)"
                     value="@Html.ValueFor(model => model.Type)"
                     tabindex="1"
                     class="easyui-combobox"
                     style="width:100%"
                     type="text"
                     data-options="prompt:'@Html.DisplayNameFor(model => model.Type)',
								 required:true,data:customertypedatasource,editable:false, validType: 'length[0,50]',panelHeight:'auto'
                                 " />
            </div>
            <!--单位层级-->
            <label class="col-md-2 mb-1 form-label text-right text-danger">@Html.DisplayNameFor(model => model.Level)</label>
            <div class="col-md-4 mb-1">
              <input id="@Html.IdFor(model => model.Level)"
                     name="@Html.NameFor(model => model.Level)"
                     value="@Html.ValueFor(model => model.Level)"
                     tabindex="1"
                     class="easyui-combobox"
                     style="width:100%"
                     type="text"
                     data-options="prompt:'@Html.DisplayNameFor(model => model.Level)',
								 required:true,data:customerleveldatasource,editable:false, validType: 'length[0,50]',panelHeight:'auto'
                                 " />
            </div>
            <!--主管部门-->
            <label class="col-md-2 mb-1 form-label text-right ">@Html.DisplayNameFor(model => model.ManageDept)</label>
            <div class="col-md-4 mb-1">
              <input id="@Html.IdFor(model => model.ManageDept)"
                     name="@Html.NameFor(model => model.ManageDept)"
                     value="@Html.ValueFor(model => model.ManageDept)"
                     tabindex="2"
                     class="easyui-textbox"
                     style="width:100%"
                     type="text"
                     data-options="prompt:'@Html.DisplayNameFor(model => model.ManageDept)',
								 required:false, validType: 'length[0,20]'
                                 " />
            </div>






            <!--用水定额(月)-->
            <label class="col-md-2 mb-1 form-label text-right text-danger">@Html.DisplayNameFor(model => model.Quota)</label>
            <div class="col-md-4 mb-1">
              <input id="@Html.IdFor(model => model.Quota)"
                     name="@Html.NameFor(model => model.Quota)"
                     value="@Html.ValueFor(model => model.Quota)"
                     tabindex="6"
                     class="easyui-numberspinner"
                     style="width:100%"
                     type="text"
                     data-options="prompt:'@Html.DisplayNameFor(model => model.Quota)',
								 required:true,formatter:numberformatter,
                                 precision:2,

                                 " />

            </div>

            <!--折扣-->
            <label class="col-md-2 mb-1 form-label text-right text-danger">@Html.DisplayNameFor(model => model.Discount)</label>
            <div class="col-md-4 mb-1">
              <input id="@Html.IdFor(model => model.Discount)"
                     name="@Html.NameFor(model => model.Discount)"
                     value="@Html.ValueFor(model => model.Discount)"
                     tabindex="9"
                     class="easyui-numberspinner"
                     style="width:100%"
                     type="text"
                     data-options="prompt:'@Html.DisplayNameFor(model => model.Discount)',
								 required:true,formatter:numberformatter,
                                 precision:2,

                                 " />

            </div>

            <!--单价-->
            <label class="col-md-2 mb-1 form-label text-right text-danger">@Html.DisplayNameFor(model => model.ServicePrice)</label>
            <div class="col-md-4 mb-1">
              <input id="@Html.IdFor(model => model.ServicePrice)"
                     name="@Html.NameFor(model => model.ServicePrice)"
                     value="@Html.ValueFor(model => model.ServicePrice)"
                     tabindex="9"
                     class="easyui-numberspinner"
                     style="width:100%"
                     type="text"
                     data-options="prompt:'@Html.DisplayNameFor(model => model.ServicePrice)',
								 required:true, precision:3,

                                 " />

            </div>

            <!--注册日期-->
            <label class="col-md-2 mb-1 form-label text-right text-danger">@Html.DisplayNameFor(model => model.RegisterDate)</label>
            <div class="col-md-4 mb-1">
              <input id="@Html.IdFor(model => model.RegisterDate)"
                     name="@Html.NameFor(model => model.RegisterDate)"
                     value="@Html.ValueFor(model => model.RegisterDate)"
                     tabindex="10" required
                     class="easyui-datebox"
                     style="width:100%"
                     type="text"
                     data-options="prompt:'@Html.DisplayNameFor(model => model.RegisterDate)',
								 required:true,
								 formatter:dateformatter" />
            </div>

            <!--备注-->
            <label class="col-md-2 mb-1 form-label text-right ">@Html.DisplayNameFor(model => model.Remark)</label>
            <div class="col-md-4 mb-1">
              <input id="@Html.IdFor(model => model.Remark)"
                     name="@Html.NameFor(model => model.Remark)"
                     value="@Html.ValueFor(model => model.Remark)"
                     tabindex="11"
                     class="easyui-textbox"
                     style="width:100%"
                     type="text"
                     data-options="prompt:'@Html.DisplayNameFor(model => model.Remark)',
								 required:false,
                                 validType: 'length[0,150]'
                                 " />
            </div>

          </div>
        </fieldset>
      </form>

      <div id="cp-customerwatermeter" class="card border mb-2" style="max-width:1200px;margin:0 auto">
        <div class="card-header p-0">
          <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <a class="navbar-brand" href="#">水表信息</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
              <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
              <ul class="navbar-nav mr-auto">
                <li class="nav-item active">
                  <a class="nav-link" href="javascript:customerwatermeter_append()"> 添加水表  </a>
                </li>
                <li class="nav-item ">
                  <a class="nav-link" href="javascript:customerwatermeter_deletechecked()">删除 <span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item ">
                  <a class="nav-link" href="javascript:customerwatermeter_stop()">停用水表 <span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item ">
                  <a class="nav-link" href="javascript:customerwatermeter_resume()">恢复水表 <span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item ">
                  <a class="nav-link" href="javascript:customerwatermeter_reload()">刷新 <span class="sr-only">(current)</span></a>
                </li>
              </ul>

            </div>
          </nav>
        </div>
        <div class="card-body">
          <div class="table-responsive">
            <table id="customerwatermeter_datagrid">
            </table>
          </div>
        </div>
      </div>
      <div id="cp-customerwaterquota" class="card border mb-2" style="max-width:1200px;margin:0 auto">
        <div class="card-header p-0">
          <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <a class="navbar-brand" href="#">水表配额</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
              <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
              <ul class="navbar-nav mr-auto">
                <li class="nav-item active mr-1">
                  <a class="nav-link " href="javascript:createcustomerwaterquota()">生成本年度用水配额 <span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item active mr-1">
                  <a class="nav-link " href="javascript:updatemonthwater()">更新用水量 <span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item ">
                  <a class="nav-link" href="javascript:customerwaterquota_deletechecked()">删除 <span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item ">
                  <a class="nav-link" href="javascript:customerwaterquota_reload()">刷新 <span class="sr-only">(current)</span></a>
                </li>
              </ul>

            </div>
          </nav>
        </div>
        <div class="card-body">
          <div class="table-responsive">
            <table id="customerwaterquota_datagrid">
            </table>
          </div>
        </div>
      </div>

      <div id="cp-customerwaterrecord" class="card border mb-2" style="max-width:1200px;margin:0 auto">
        <div class="card-header p-0">
          <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <a class="navbar-brand" href="#">抄表记录</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
              <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
              <ul class="navbar-nav mr-auto">
                <li class="nav-item  active">
                  <a class="nav-link font-white " href="javascript:autorecordmonth()">自动抄表 <span class="sr-only">(current)</span></a>
                </li>
              </ul>

</div>
          </nav>
        </div>
        <div class="card-body">
          <div class="table-responsive">
            <table id="customerwaterrecord_datagrid">
            </table>
          </div>
        </div>
      </div>


    </div>
  </div>
</div>
<div id="windowfooter" style="padding:5px;">&nbsp;</div>
<!-- 弹出窗体form表单 -->
<!-- 弹出编辑对话框 -->
<!-- customerwaterrecord datagrid  javascript block -->
<!-- customerwatermeter datagrid  javascript block -->
@Html.Partial("_CustomerWaterMeterEditForm", new WebApp.Models.CustomerWaterMeter())
<!-- customerwaterquota datagrid  javascript block -->


<!--begin popup detailview javascript block -->
<script type="text/javascript">
  //判断新增编辑状态
  var MODELSTATE = 'Added';
  var customerid = null;
  function opencustomerdetailwindow(data, state) {
    MODELSTATE = state;
    initcustomerdetailview();
    customerid = (data.Id || 0);
    $('#customerdetailwindow').window('open');
    $('#customer_form').form('reset');
    $('#customer_form').form('load', data);
    var url = '/CustomerWaterRecords/GetDataByCustomerId?customerid=' + customerid;
    $customerwaterrecorddg.datagrid('load', url);
    $customerwaterrecorddg.datagrid('resize');
    $customerwaterrecorddg.datagrid('uncheckAll');
    var url = '/CustomerWaterMeters/GetDataByCustomerId?customerid=' + customerid;
    $customerwatermeterdg.datagrid('load', url);
    $customerwatermeterdg.datagrid('resize');
    var url = '/CustomerWaterQuotas/GetDataByCustomerId?customerid=' + customerid;
    $customerwaterquotadg.datagrid('load', url);
    $customerwaterquotadg.datagrid('resize');
  }
  //删除当前记录
  function deletecustomeritem() {
    $.messager.confirm('确认', '你确定要删除该记录?', result => {
      if (result) {
        const url = `/Customers/Delete/${customerid}`;
        $.get(url).done(res => {
          if (res.success) {
            toastr.success("删除成功");
            $dg.datagrid('reload');
            $('#customerdetailwindow').window('close');
          } else {
            $.messager.alert('错误', res.err, 'error');
          }
        });
      }
    });
  }
  //async 保存数据
  async function savecustomeritem() {
    const $customerform = $('#customer_form');
    if ($customerform.form('enableValidation').form('validate')) {
      let customer = $customerform.serializeJSON();
      //获取明细表数据

      const customerwaterrecord_result = await customerwaterrecord_accept();
      if (!customerwaterrecord_result.success) {
        return false;
      } else {
        customer.CustomerWaterRecords = customerwaterrecord_result.changed;
      }


      const customerwatermeter_result = await customerwatermeter_accept();
      if (!customerwatermeter_result.success) {
        return false;
      } else {
        customer.WaterMeters = customerwatermeter_result.changed;
      }


      const customerwaterquota_result = await customerwaterquota_accept();
      if (!customerwaterquota_result.success) {
        return false;
      } else {
        customer.WaterQuotas = customerwaterquota_result.changed;
      }

      let url = '/Customers/Edit';
      //判断是新增或是修改方法
      if (MODELSTATE === 'Added') {
        url = '/Customers/Create';
      }
      var token = $('input[name="__RequestVerificationToken"]', $customerform).val();
      $.messager.progress({ title: '请等待', msg: '正在保存数据...', interval: 200 });
      $.ajax({
        type: "POST",
        url: url,
        data: {
          __RequestVerificationToken: token,
          customer: customer
        },
        dataType: 'json',
        contentType: 'application/x-www-form-urlencoded; charset=utf-8'
      })
        .done(response => {
          $.messager.progress('close');
          if (response.success) {
            hook = false;
            $customerform.form('disableValidation');
            $dg.datagrid('reload');
            $('#customerdetailwindow').window("close");
            toastr.success("保存成功");
          } else {
            $.messager.alert("错误", response.err, "error");
          }
        })
        .fail((jqXHR, textStatus, errorThrown) => {
          $.messager.progress('close');
          $.messager.alert('异常', `${jqXHR.status}: ${jqXHR.statusText} `, 'error');
        });
    }
  }
  //关闭窗口
  function closecustomerdetailwindow() {
    $('#customerdetailwindow').window('close');
  }
  //自动抄表
    function autorecordmonth() {
      $.messager.progress({ title: '正在计算....' });
       $.post('/CustomerWaterRecords/AutoRecordMonth')
         .done(response => {
           $.messager.progress('close');
                                if (response.success) {
                                  toastr.success(`抄表完成`);
                                  $customerwaterrecorddg.datagrid('reload');
                                } else {
                                    $.messager.alert('错误', response.err,'error');
                                }
                          })
         .fail((jqXHR, textStatus, errorThrown) => {
                            $.messager.progress('close');
                             $.messager.alert('异常', `${jqXHR.status}: ${jqXHR.statusText} `, 'error');
                          });
  }
  //更新实际用水量
  function updatemonthwater() {
    $.messager.progress({ title: '正在计算....' });
       $.post('/CustomerWaterQuotas/UpdateMonthWater')
         .done(response => {
           $.messager.progress('close');
                                if (response.success) {
                                  toastr.success(`更新完成`);
                                  $customerwaterquotadg.datagrid('reload');
                                } else {
                                    $.messager.alert('错误', response.err,'error');
                                }
                          })
         .fail((jqXHR, textStatus, errorThrown) => {
                            $.messager.progress('close');
                             $.messager.alert('异常', `${jqXHR.status}: ${jqXHR.statusText} `, 'error');
                          });
  }
  //生成配额
  function createcustomerwaterquota() {
    const year = moment().year();
    const id = parseInt($('#customer_form #Id').val());
    if (id <= 0) {
      $.messager.alert('提示','请先保存单位信息后再生成配额')
      return;
    }
    $.get(`/Customers/CreateCustomerWaterQuotas?customerid=${id}&year=${year}`).done(res => {
      if (res.success) {
        customerwaterquota_reload();
        toastr.success('生成成功!');
      } else {
        $.messager.alert('生成失败', result.err, 'error');
      }

    });
  }
  //判断是否有没有保存的记录
  function customerhasmodified() {
    if (!hook) {
      if (!customerwaterrecord_endEditing()) {
        return true;
      }
      const customerwaterrecords = $customerwaterrecorddg.datagrid("getChanges");
      if (MODELSTATE == 'Modified' && customerwaterrecords.length > 0) {
        return true;
      }
      if (!customerwatermeter_endEditing()) {
        return true;
      }
      const customerwatermeters = $customerwatermeterdg.datagrid("getChanges");
      if (MODELSTATE == 'Modified' && customerwatermeters.length > 0) {
        return true;
      }
      if (!customerwaterquota_endEditing()) {
        return true;
      }
      const customerwaterquotas = $customerwaterquotadg.datagrid("getChanges");
      if (MODELSTATE == 'Modified' && customerwaterquotas.length > 0) {
        return true;
      }
      return false;
    } else {
      return hook;
    }

  }


  function initcustomerdetailview() {
    //判断是否显示功能按钮
    if (MODELSTATE === 'Added') {
      $('#deleteitem-btn-group').hide();
    } else {
      $('#deleteitem-btn-group').show();
    }

     
  }
</script>

